<template>
  <!-- 添加或修改客户对话框 -->
  <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="850px" append-to-body>
    <el-row>
      <el-col :span="18">
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          label-width="auto"
          :disabled="disabled"
          :class="{ 'detail-disabled': disabled }"
        >
          <!-- <el-form-item label="封面" prop="coverImg">
            <image-upload
              :limit="1"
              @input="
                (val) => {
                  form.coverImg = val
                }
              "
              :value="form.coverImg"
            />
          </el-form-item> -->
          <el-form-item label="拓展名称" prop="expansionName">
            <el-input v-model="form.expansionName" placeholder="请输入拓展名称" />
          </el-form-item>
          <el-form-item label="拓展类型" prop="expansionType">
            <el-select v-model="form.expansionType" placeholder="请选择拓展类型" clearable>
              <el-option-group v-for="group in typeList" :key="group.label" :label="group.label">
                <el-option v-for="item in group.children" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-option-group>
            </el-select>
          </el-form-item>
          <el-form-item label="对应客户" v-if="showCustomer.indexOf(form.expansionType) > -1" prop="customerId">
            <el-select
              v-model="form.customerId"
              placeholder="输入关键词可获取更多"
              :remote-method="getCustomer"
              filterable
              remote
              reserve-keyword
              clearable
              :loading="customerLading"
              @clear="
                () => {
                  getCustomer('')
                }
              "
            >
              <el-option v-for="dict in customerData" :key="dict.id" :label="dict.customerName" :value="dict.id" />
            </el-select>
          </el-form-item>
          <el-form-item
            label="对应项目"
            prop="projectId"
            v-else-if="!disabled"
            :rules="[
              {
                required: false,
                message: '请选择项目',
                trigger: ['change'],
              },
            ]"
          >
            <TableSelect
              :value="form.project"
              :isReturnRow="true"
              :dicts="dict.type"
              :defaultProps="{ label: 'projectName', value: 'id' }"
              :column="columns"
              placeholder="请选择项目"
              :request="getProjectListPop"
              @change="
                (data) => {
                  form.project = { ...data }
                  form.projectId = data.id
                  form.customerName = data.customerName
                  form.customerId = data.customerId
                }
              "
            >
            </TableSelect>
          </el-form-item>
          <el-form-item label="对应客户" prop="customerName" v-if='form.projectId && form.customerId'>
            <el-input v-model="form.customerName" disabled />
          </el-form-item>
          <el-form-item label="支出预算" prop="expensesBudget">
            <el-input-number
              controls-position="right"
              :step="100"
              style="width: 170px"
              :precision="2"
              :min="0"
              v-model="form.expensesBudget"
              placeholder="请输入支出预算"
            >
            </el-input-number>
            元
          </el-form-item>
          <el-form-item label="支出" prop="expenses">
            <el-input-number
              controls-position="right"
              :step="100"
              style="width: 170px"
              :precision="2"
              :min="0"
              v-model="form.expenses"
              placeholder="请输入支出"
            >
            </el-input-number>
            元
          </el-form-item>
          <el-form-item label="拓展时间" prop="expansionTime">
            <el-date-picker
              clearable
              v-model="form.expansionTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择拓展时间"
            >
            </el-date-picker>
          </el-form-item>
          <!-- <el-form-item label="详细地址" prop="detailedAddress">
            <el-input v-model="form.detailedAddress" placeholder="请输入详细地址" />
          </el-form-item> -->

          <el-form-item label="负责人" prop="responsiblePerson">
            <el-input v-model="form.responsiblePerson" placeholder="请输入负责人" />
          </el-form-item>
          <el-form-item label="参加人员" prop="participants">
            <el-input v-model="form.participants" type="textarea" placeholder="请输入内容" />
          </el-form-item>

          <el-form-item label="拓展详情" prop="expansionDetails">
            <el-input v-model="form.expansionDetails" type="textarea" placeholder="请输入内容" />
          </el-form-item>
          <el-form-item label="成果" prop="results">
            <el-input v-model="form.results" type="textarea" placeholder="请输入内容" />
          </el-form-item>
        </el-form>
      </el-col>
      <el-col v-if="disabled" :span="24">
        <div class="decorate" style="margin-top: 20px">
          <span>项目</span>
        </div>
        <el-table
          :data="projectList"
          style="width: 100%"
          @row-click="projectRowClick"
          v-loading="projectLoading"
          row-class-name="tableColumn"
          :header-cell-style="{ background: '#fff' }"
        >
          <el-table-column prop="projectName" align="center" label="项目名称"> </el-table-column>
          <el-table-column prop="projectNumber" align="center" label="项目编号"> </el-table-column>

          <el-table-column prop="projectManager" align="center" label="项目类型">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.project_type" :value="scope.row.projectType" />
            </template>
          </el-table-column>

          <el-table-column align="center" prop="projectLevel" label="项目级别">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.project_level" :value="scope.row.projectLevel" />
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="projectTotal > 0"
          :total="projectTotal"
          :page.sync="projectParams.pageNum"
          :limit.sync="projectParams.pageSize"
          @pagination="getProjectList"
        />
      </el-col>
    </el-row>
    <div slot="footer" class="dialog-footer" v-if="!disabled">
      <el-button @click="open = false">取 消</el-button>
      <el-button type="primary" v-loading="loading" @click="submitForm">确 定</el-button>
    </div>
    <project-details
      :show="modelName === 'projectDetails'"
      :disabled="true"
      @cancel="handleOpenModel"
      :id="modelData.id"
    ></project-details>
  </el-dialog>
</template>
<script>
import { getExpansion, addExpansion, updateExpansion, getExpansionType } from '@/api/biz/expansion'
import ProjectDetails from '@/components/biz/ProjectDetails.vue'
import { listProject } from '@/api/biz/project'
import TableSelect from '@/components/TableSelect'
import { listCustomer } from '@/api/biz/customer'
import { recycleBinReview } from '@/api/biz/bin'
export default {
  name: 'ExpansionDetails',
  components: {
    ProjectDetails,
    TableSelect,
  },
  props: {
    id: {
      type: Number | String,
      default: '',
    },
    show: {
      type: Boolean,
      default: false,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    bin: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    var checkAmount = (rule, value, callback) => {
      if (!value) {
        return callback(new Error())
      }
      setTimeout(() => {
        if (typeof value !== 'number' || Number.isNaN(value)) {
          callback(new Error())
        } else {
          callback()
        }
      }, 1000)
    }
    return {
      open: false,
      loading: false,
      title: '',
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        expansionName: [{ required: true, message: '拓展名称不能为空', trigger: 'blur' }],
        expansionType: [{ required: true, message: '请选择拓展类型', trigger: 'change' }],
        customerId: [{ required: true, message: '请选择对应客户', trigger: 'change' }],
        expenses: [{ required: true, message: '请输入支出金额', validator: checkAmount, trigger: 'blur' }],
      },
      projectParams: {
        pageNum: 1,
        pageSize: 10,
        supplierId: '',
      },
      projectList: [],
      projectTotal: 0,
      projectLoading: false,
      modelData: {},
      modelName: '',
      columns: [
        { label: '项目名称', prop: 'projectName', isLabel: true },
        { label: '项目编号', prop: 'projectNumber' },
        { label: '项目类型', prop: 'projectType', dictName: 'project_type' },
        { label: '项目级别', prop: 'projectLevel', dictName: 'project_level' },
      ],
      customerLading: false,
      customerData: [],
      typeList: [],
      showCustomer: [],
    }
  },
  dicts: ['project_type', 'project_level'],
  watch: {
    show: {
      handler(val) {
        this.open = val
        this.modelName = ''
      },
    },
    open: {
      handler(val) {
        this.reset()
        if (val) {
          if (this.disabled) {
            this.title = '市场拓展详情'
          } else {
            this.title = !this.id ? '添加市场拓展' : '修改市场拓展'
          }
          this.getExpansionTypes()
          if (this.id) {
            this.form.id = this.id
            const callback = (response) => {
              if (response.data.project && response.data.project.id) {
                response.data.projectId = response.data.project.id
                if (this.disabled) {
                  this.projectList = [response.data.project]
                }
              } else {
                response.data.project = {}
              }
              if (response.data.customerId) {
                this.customerData = [
                  {
                    id: response.data.customerId,
                    customerName: response.data.customerName,
                  },
                ]
              }
              this.form = response.data
            }
            if (!this.bin) {
              getExpansion(this.id).then(callback)
            } else {
              recycleBinReview(this.id).then(callback)
            }
          } else {
            this.getCustomer()
          }
        } else {
          this.projectParams.expansionId = ''
          this.projectList = []
          this.open = false

          this.$emit('cancel', false)
        }
      },
    },
  },
  methods: {
    getExpansionTypes() {
      getExpansionType().then((response) => {
        const [filter = {}] = response.data.filter((item) => item.label == '公共关系')
        const arr = filter.children ? filter.children.map((item) => item.value) : []
        this.showCustomer = arr
        this.typeList = response.data
      })
    },
    projectRowClick(row) {
      this.handleOpenModel('projectDetails', row)
    },
    handleOpenModel(name = '', data = {}) {
      this.modelName = name
      this.modelData = data
    },
    getProjectListPop(data) {
      return listProject(data)
    },
    getProjectList(query = '') {
      this.projectLoading = true
      this.projectParams.projectName = query
      listProject(this.projectParams)
        .then((response) => {
          this.projectList = response.rows
          this.projectTotal = response.total
          this.projectLoading = false
        })
        .catch(() => {
          this.projectLoading = false
        })
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        // addressId: null,
        author: null,
        detailedAddress: null,
        expansionDetails: null,
        expansionName: null,
        expansionTime: null,
        expansionType: null,
        expenses: null,
        latitude: null,
        longitude: null,
        participants: null,
        responsiblePerson: null,
        results: null,
        projectId: null,
        coverImg: null,
        project: null,
        expensesBudget: null,
      }
      this.resetForm('form')
    },
    /** 提交按钮 */
    submitForm() {
      this.loading = true
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateExpansion(this.form)
              .then((response) => {
                this.loading = false
                this.$modal.msgSuccess('修改成功')
                this.open = false

                this.$emit('refresh')
              })
              .catch(() => {
                this.loading = false
              })
          } else {
            addExpansion(this.form)
              .then((response) => {
                this.loading = false
                this.$modal.msgSuccess('新增成功')
                this.open = false
                this.$emit('refresh')
              })
              .catch(() => {
                this.loading = false
              })
          }
        } else {
          this.loading = false
        }
      })
    },
    getCustomer(query = '') {
      this.customerLading = true
      listCustomer({ customerName: query, pageNum: 1, pageSize: 10 })
        .then((res) => {
          this.customerData = res.rows
          this.customerLading = false
        })
        .catch((error) => {
          this.customerLading = false
        })
    },
  },
}
</script>
<style lang="scss" scoped>
.decorate {
  display: flex;
  flex-direction: row;
  font-size: 16px;
  color: #333;
  padding: 15px 0;
  &::before {
    display: block;
    content: '';
    width: 4px;
    height: 20px;
    background: #317bf9;
    margin-right: 8px;
  }
}
</style>
<style>
.tableColumn {
  cursor: pointer;
}
</style>
